<?php

namespace App\Http\Controllers\Cruise\Web;

use App\Http\Controllers\BaseController;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Http\Validate\Cruise\CruiseProjectValidate;
use App\Models\Cruise\CruiseProjectCategoryModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Service\Cruise\CruiseProject\CruiseBaseService;
use App\Service\Cruise\CruiseProject\CruiseCategoryService;
use App\Service\Cruise\CruiseProject\CruiseProjectParam;
use App\Service\Cruise\CruiseProject\CruiseProjectService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;

class CruiseCategoryController extends BaseController
{
    /**
     * 分类列表
     * @param Request $request
     * @return JsonResponse
     */
    public function lists(Request $request): JsonResponse
    {
        $types = CruiseBaseService::getPermissionTypes(getRmsUserPermissionList([], UserPermissionAuth::MODULE_CRUISE));

        return $this->success(CruiseCategoryService::list($types));
    }

    /**
     *
     * 更改项目分类名称
     *
     * @param Request $request
     * @param $id
     * @return JsonResponse
     * @throws ValidationException
     */
    public function update(Request $request, $id): JsonResponse
    {
        $this->validate($request, [
            'name' => 'required|string',
            'pid'  => 'required|numeric',
        ]);
        CruiseCategoryService::update($id, $request->name, $request->pid);
        return $this->success();
    }

    /**
     * 添加分类
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function add(Request $request): JsonResponse
    {
        $this->validate($request, [
            'id'   => 'numeric',
            'name' => 'required|string',
            'type' => ['required_if:pid,0', 'integer', Rule::in(array_keys(CruiseTemplateModel::TYPE_TEXT))],
        ]);
        CruiseCategoryService::add($request->id, $request->name, $request->type);
        return $this->success();
    }

    /**
     * 删除分类
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function delete(Request $request, $id): JsonResponse
    {
        $res = CruiseCategoryService::delete($id);
        if ($res) {
            return $this->fail(403, '该分类下已有分类或项目，不可删除');
        } else {
            return $this->success();
        }
    }
}
